package classloader;

import java.io.IOException;
import java.io.InputStream;

/**
 * Decription 类加载器测试
 * Date 2017/10/6 21:11
 * authur MangoDai
 **/
public class ClassLoaderTest {
    public static void main(String[] args) throws Exception {
        Object obj = new MyClassLoader().loadClass("classloader.A").newInstance();
        System.out.println(obj.getClass());
        /**
         * 因为这个虚拟机中存在两个ClassLoaderTest类代码
         * 一个是app加载的，一个是我们加载的
         */
        System.out.println(obj instanceof  classloader.A);
    }
}
class MyClassLoader extends ClassLoader {
    /**
     * 我们自定义的类加载器没有实现双亲委托机制
     * @param name
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        try {
            String fileName = name.substring(name.lastIndexOf(".")+1) + ".class";
            System.out.println("getClass() = " + getClass());
            InputStream is = getClass().getResourceAsStream(fileName);
            if (is == null) {
                return super.loadClass(name);
            }
            byte[] b = new byte[is.available()];
            is.read(b);
            return defineClass(name, b, 0, b.length);
        } catch (IOException e) {
            throw new ClassNotFoundException(name);
        }
    }
}
